/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Business.RegionDBUtil;

import Business.Record.Record;
import Business.Region.Country.Country;
import Business.Region.Provincy.Provincy;
import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.config.EmbeddedConfiguration;
import com.db4o.ta.TransparentPersistenceSupport;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author hooting
 */
public class RegionDBUtil {
	//Change the FILENAME to the path where you have saved your DB4O serialization file
    private static final String FILENAME = "db/DataRegion.db";	
     /*
    * Reads the Db4O file and creates and returns an ObjectContainer object
    * @return ObjectContainer
    */
    private ObjectContainer createConnection() {
       try {
           EmbeddedConfiguration config = Db4oEmbedded.newConfiguration();
           config.common().add(new TransparentPersistenceSupport());
           //Controls the number of objects in memory
           config.common().activationDepth(Integer.MAX_VALUE);
           //Controls the depth/level of updation of Object
           config.common().updateDepth(Integer.MAX_VALUE);

           //Register your top most Class here
           config.common().objectClass(Country.class).cascadeOnUpdate(true);

           ObjectContainer db = Db4oEmbedded.openFile(config, FILENAME);
           return db;
       } catch (Exception ex) {
           System.out.println(ex.getMessage());
	       ex.printStackTrace();
       }
       return null;
    }

    public void insertCountry(Country c){
	    ObjectContainer conn = createConnection();
	    conn.store(c);
	    conn.commit();
		conn.close();
    }

    public void deleteCountry(Country c){
	    ObjectContainer conn = createConnection();
	    ObjectSet result = conn.queryByExample(c);
	    Country found = (Country)result.next();
		conn.delete(found);
		conn.commit();
		conn.close();
    }

	public void deleteAllCountries(){
		ObjectContainer conn = createConnection();
		ObjectSet<Country> systems = conn.query(Country.class);
		for(int i = 0; i < systems.size(); i++){
			conn.delete(systems.get(i));
		}
		conn.commit();
		conn.close();
	}

    public List<Country> retrieveAllCountries(){
	    ObjectContainer conn = createConnection();
	    ObjectSet<Country> systems = conn.query(Country.class);
	    List<Country> l = new ArrayList<Country>();
	    for(int i = 0; i < systems.size(); i++){
		    l.add(systems.get(i));
	    }
	    conn.close();
	    return l;
    }

    public void updateCountry(Country c){
		deleteCountry(new Country(c.getCountryName()));
		insertCountry(c);
    }
}
